//
//  XDPersonChooseViewController.m
//  iphone.mobileoa
//
//  Created by 李亚春 on 13-6-6.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "XDPersonChooseViewController.h"
#import "DBFrameService.h"
#import "QueryContactsTask.h"

@interface XDPersonChooseViewController ()
{
    NSMutableArray *dataArray;
    NSMutableArray *choosedPersons;
    NSMutableArray *backFlagList;
    NSString *whichControl;
}
@end

@implementation XDPersonChooseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"人员选择";
    whichControl = [[intentParams objectForKey:@"whichControl"]retain];
    NSMutableArray *withPerson = [[intentParams objectForKey:@"withPerson"]retain];
    
    choosedPersons = [[NSMutableArray alloc]init];
    if (withPerson.count>0) {
        for (int i=0; i<withPerson.count; i++) {
            [choosedPersons addObject:[withPerson objectAtIndex:i]];
        }
        
    }
    
    
    backFlagList = [[NSMutableArray alloc]init];
    UIButton *titleButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200, 40)];
    [titleButton addTarget:self action:@selector(clickChoosedPerson) forControlEvents:UIControlEventTouchUpInside];
    [titleButton setTitle:[NSString stringWithFormat:@"人员选择(%i)",choosedPersons.count] forState:UIControlStateNormal];
    [titleButton.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
    [titleButton setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
    
    self.navigationItem.titleView=titleButton;
    
    UIButton* rightButton= [[UIButton alloc] initWithFrame:CGRectMake(0,0,40,20)];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"top_right"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(topRightAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = leftBarButtonItem;
    [leftBarButtonItem release];
    [rightButton release];
    
    [self getData:@""];
}

-(void)popBack
{
    [self backLogic];
}

-(void)backLogic
{
    if ([backFlagList count]==0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if([backFlagList count]==1)
    {
        [self getData:@""];
        [self.tv reloadData];
    }
    else
    {
        NSString *guid = [backFlagList objectAtIndex:[backFlagList count]-2];
        [self getData:guid];
        [self.tv reloadData];
    }
    
    if ([backFlagList count]>0) {
        NSInteger count = [backFlagList count];
        [backFlagList removeObjectAtIndex:count - 1];
    }
}

-(void)topRightAction
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:choosedPersons forKey:whichControl];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)clickChoosedPerson
{
    [dataArray removeAllObjects];
    for (int i=0;i<choosedPersons.count; i++) {
        NSMutableDictionary *person = [choosedPersons objectAtIndex:i];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:[person objectForKey:@"userguid"] forKey:@"guid"];
        [dic setObject:[person objectForKey:@"displayname"] forKey:@"name"];
        [dic setObject:@"user" forKey:@"type"];
        [dic setObject:@"" forKey:@"ouname"];
        [dic setObject:@"" forKey:@"title"];
        [dataArray addObject:dic];
        [dic release];
    }
    [self.tv reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getData:(NSString *)_parentguid
{
    dataArray = [[DBFrameService getContactsListByParentGuid:_parentguid]retain];
}

#pragma tableview

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"tableitem";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    NSMutableDictionary *dic = [dataArray objectAtIndex:[indexPath row]];
    
    cell.textLabel.text = [dic objectForKey:@"name"];
    NSString *type = [dic objectForKey:@"type"];
    NSString *guid = [dic objectForKey:@"guid"];
    if ([type isEqualToString:@"user"]) {
        
        if (![[dic objectForKey:@"ouname"] isEqualToString:@""]||![[dic objectForKey:@"title"] isEqualToString:@""]) {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@:%@",[dic objectForKey:@"ouname"],[dic objectForKey:@"title"]];
        }
        else
        {
            cell.detailTextLabel.text = @"";
        }
        
        BOOL isChoose = NO;
        for (int i=0; i<choosedPersons.count; i++) {
            NSMutableDictionary *cd = [choosedPersons objectAtIndex:i];
            if ([[cd objectForKey:@"userguid"] isEqualToString:guid]) {
                isChoose = YES;
                break;
            }
        }
        
        if (isChoose) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    else
    {
        cell.detailTextLabel.text = @"";
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *m = [dataArray objectAtIndex:indexPath.row];
    NSString *guid = [m objectForKey:@"guid"];
    NSString *type = [m objectForKey:@"type"];
    if ([type isEqualToString:@"ou"]) {
        [self getData:guid];
        [backFlagList addObject:guid];
        [tableView reloadData];
        
    }
    else
    {
        NSMutableDictionary *person = [[NSMutableDictionary alloc]init];
        [person setObject:[m objectForKey:@"guid"] forKey:@"userguid"];
        [person setObject:[m objectForKey:@"name"] forKey:@"displayname"];
            if (![choosedPersons containsObject:person]) {
                [choosedPersons addObject:person];
            }
            else{
                [choosedPersons removeObject:person];
            }
            [person release];
            self.title = [NSString stringWithFormat:@"人员选择(%i)",choosedPersons.count];
            [((UIButton *)self.navigationItem.titleView) setTitle:[NSString stringWithFormat:@"人员选择(%i)",choosedPersons.count] forState:UIControlStateNormal];
            [tableView reloadData];
    }
}


-(void)refreshUIWithThreadGuid:(NSString *)threadGuid andData:(NSObject *)obj
{
    [self hideMBPHUD];
    dataArray = (NSMutableArray *)[obj retain];
    [self.tv reloadData];
}

#pragma searchbar

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    [self doSearch:searchBar];
}

- (void)doSearch:(UISearchBar *)searchBar{
    [self showMBPHUD];
    NSMutableDictionary *params = self.getPassDictionary;
    [params setObject:searchBar.text forKey:@"keyword"];
    [[[QueryContactsTask alloc]initWithContext:self andParams:params]startTask];
}

- (void)dealloc {
    [_tv release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setTv:nil];
    [super viewDidUnload];
}
@end
